<!--
* description: 备件新增
* author: wangmaolin
* createdDate: 2021
* logs:
-->
<template>
  <section class="history">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="true"
      title="备件查询选择"
      :append-to-body="true"
      :visible="popupsVisible"
      width="70%"
      @close="handleClose"
    >
      <dialogHeader
        slot="title"
        title="备件查询选择"
        :style-type="$store.state.app.dialogType"
      />
      <div class="app-container app-container-table">
        <!-- 单表格模版页面 -->
        <one-table-template
          ref="multipleTable"
          :dynamic-api-config="apiConfig"
          :dynamic-buttons="dynamicButtons"
          :dynamic-components="tableComponents"
          :dynamic-table-cols="dynamicTableCols"
          :dynamic-form-fields="formField"
          :dynamic-is-show-select="true"
          :dynamic-is-init-table="true"
          :dynamic-is-show-more-btn="true"
          :dynamic-api-style="'restful'"
          :dynamic-table-defult-height="300"
          :callback-obj="callbackObj"
        />
      </div>
      <div class="subs">替换件信息</div>
      <el-table
        :data="subData"
        style="width: 99%"
        height="260"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="50"
        />
        <el-table-column
          prop="partNo"
          align="center"
          label="备件编码"
        />
        <el-table-column
          prop="partName"
          align="center"
          label="备件名称"
        />
        <el-table-column
          prop="purchasePrice"
          align="center"
          label="单价"
        />
        <el-table-column
          align="center"
          prop="accountQty"
          label="库存数量"
        />
        <el-table-column
          align="center"
          prop="usableStockQty"
          label="可用库存"
        />
        <el-table-column
          align="center"
          prop="SNP"
          label="包装含量"
        />
        <el-table-column
          align="center"
          prop="partRepairType"
          label="备件类别"
        />
      </el-table>
    </el-dialog>
  </section>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
// import { orgApis } from '@/api/caseManagementQuery'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'

export default {
  name: 'PartQuery',
  components: {
    OneTableTemplate,
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],
  props: {
    popupsVisible: { type: Boolean, default: false },
    rowData: { type: Object, default: () => ({}) },
    dynamicEditRowData: { type: Object, default: () => ({}) },
    // 已经选择过的数据
    chosenList: { type: Array, default: () => ([]) }
  },
  data() {
    return {
      subData: [],
      formField: {
        carTypeCn: '',
        carTypeCode: ''
      },
      selections: [],
      // 保存API配置对象
      apiConfig: {
        APIUrl: '/mp/e3sh/aftersale/maintenanceItemService/querySpareParts.do',
        ServiceCode: 'querySpareParts'
      },
      // 动态组件-按钮
      dynamicButtons: [
        {
          compKey: 'btnKey0',
          size: 'small',
          name: 'search',
          clickEvent: () => {
            if (!this.selections.length) {
              return this.$message('请至少选择一条数据！')
            }
            this.$emit('selectRows', this.selections, 'part')
            this.handleClose()
          },
          text: '选择'
        },
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: '查询'
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: '重置'
        }
      ],
      tableComponents: [
        {
          compKey: 'compKey1',
          labelName: '备件编码：',
          codeField: 'partNo',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          span: 8,
          isMust: true
        },

        {
          compKey: 'compKey2',
          labelName: '备件名称：',
          codeField: 'partName',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          span: 8,
          isMust: true
        },
        // {
        //   compKey: 'compKey3',
        //   labelName: '备件类别：',
        //   codeField: 'partRepairType',
        //   lookuptype: 'SE0171',
        //   component: () => import('@/components/org/commonSelect'),
        //   customObj: {
        //     api: {
        //       APIUrl: '/mp/e3sh/aftersale/appointmentVolumnService/queryListOfValues.do'
        //     }
        //   },
        //   type: 'inputText',
        //   span: 8,
        //   isMust: true
        // },
        {
          compKey: 'compKey7',
          labelName: '车系：',
          codeField: 'carSeriesCode',
          component: () => import('@/components/org/commonSelect'),
          oFields: 'carSeriesCode,carSeriesCn',
          customObj: {
            api: vehiclePdiPriceInquirys.queryCarSeries,
            selectType: '1'
          },
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey8',
          labelName: '车型：',
          codeField: 'carTypeCn',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          disabled: true,
          isMust: true,
          span: 8
        },
        // {
        //   compKey: 'carSeries',
        //   labelName: '车系：',
        //   codeField: 'carSeriesId',
        //   textField: 'carSeriesCn',
        //   oFields: 'carSeriesId,carSeriesCn',
        //   customObj: { api: orgApis.listOfCarSeries, selectType: '1' },
        //   component: () => import('@/components/org/commonSelect'),
        //   isMust: true,
        //   span: 8
        // },
        // {
        //   compKey: 'carConfig',
        //   labelName: '车型：',
        //   codeField: 'carConfigId',
        //   textField: 'carConfigCn',
        //   component: () => import('@/components/org/commonSelect'),
        //   oFields: 'carConfigId,carConfigCn',
        //   parentFileds: 'value:carSeriesId',
        //   customObj: {
        //     listQuery: { carSeriesId: '' },
        //     api: orgApis.listOfCarModel, selectType: '1'
        //   },
        //   isMust: true,
        //   span: 8
        // },
        {
          compKey: 'compKey6',
          labelName: '可用库存数量大于零',
          codeField: 'usableStockQty',
          component: () => import('@/components/org/checkBox'),
          isMust: true,
          span: 8
        }
      ],
      dynamicTableCols: [
        {
          prop: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'controlId',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'partNo',
          label: '备件编码'
        },
        {
          prop: 'partName',
          label: '备件名称'
        },
        {
          // prop: 'userPrice',
          prop: 'purchasePrice',
          label: '单价'
        },
        {
          prop: 'accountQty',
          label: '库存数量'
        },
        {
          prop: 'usableStockQty',
          label: '可用库存'
        },
        {
          // prop: 'snp',
          prop: 'SNP',
          label: '包装含量'
        },
        {
          // prop: 'partRepairTypeName',
          prop: 'partRepairType',
          label: '备件类别'
        },
        {
          prop: 'carConfigIdList',
          label: '适用车型'
        }

      ],
      callbackObj: {
        // 处理网格多选
        onCheckSelectChange: (selection) => {
          this.selections = selection
        },
        // 处理网格双击
        onRowDbClick: (row, column, event, rowIndex) => {
          // 查询替换件
          this.queryReplacementParts(row)
        }
      },
      // 表单数据（无需赋值，由混入对象赋值）
      initFormField: null,
      genCodeFiled: () => {}
    }
  },
  watch: {
    popupsVisible(isOpen) {
      if (isOpen) {
        for (const attr in this.formField) {
          this.formField[attr] = this.rowData[attr] || ''
        }
        this.formField.carTypeCn = this.dynamicEditRowData.carConfigCn
        this.formField.carTypeCode = this.dynamicEditRowData.carConfigCode
      }
      isOpen ? this.queryTable() : ''
    }
  },
  created() {
    this.genFormField()
  },
  mounted() {
    this.queryTable(1)
  },
  methods: {
    // 查询替换件
    queryReplacementParts(row) {
      this.$requestAPI({
        apiUrl: '/mp/e3sh/aftersale/appointmentVolumnService/queryReplacementParts.do',
        variables: row
      }).then(res => {
        if (res.result === '1') {
          console.log(res)
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    // 禁用上个弹窗已选择 数据
    getSelectable(row, index, ref) {
      return !this.chosenList.includes(row['partNo'])
    },
    genFormField() {
      const viewPageCode = this.$route.path
      this.genCodeFiled = this.genUtil(this.tableComponents)
      const formField = this.genCodeFiled()
      this.formField = this.$utils.getFormField(this, formField, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField') => array.reduce((p, c) => {
      if (c[attr1].includes(',')) {
        const d = c[attr1].split(',')
        for (let i = 0; i < d.length; i++) {
          p[d[i]] = ''
        }
      } else {
        p[c[attr1]] = ''
      }
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      return p
    }, {}),
    changeCode(code, text, codeField, comType) {
      const d = parseInt(comType)
      this.orderList[d][codeField] = code
    },
    handleClose() {
      this.$emit('update:popupsVisible', false)
    },
    closePopups() {
      for (const attr in this.formField) {
        this.formField[attr] = ''
      }
    },
    reset() {
      this.formField.partNo = ''
      this.formField.partName = ''
      this.formField.carSeriesCode = ''
      this.formField.usableStockQty = ''
    }
  }
}
</script>
<style scoped>
</style>
